package cn.tedu.boot03.controller;

import cn.tedu.boot03.entity.Product;
import cn.tedu.boot03.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

//@Controller
@RestController   //  相当于在每一个方法上都添加了@ResponseBody注解
public class ProductController {

    /*
    * 自动装配,添加之后,Mybatis和Spring框架会生成ProductMapper的实现类,
    * 并且实例化该实现类(实现类里面会实现ProductMapper中的抽象方法,实现
    * 的方法里面写的就是JDBC代码),并且把实例化好的对象赋值给了mapper变量
    * */
    @Autowired
    private ProductMapper mapper;

    @RequestMapping("/insert")
    public String insert(Product product){
        System.out.println("商品:" + product);

        mapper.insert(product);

        return "添加完成!<a href = '/'>首页</a>";

    }

    @RequestMapping("/select")
    public String select(){

        List<Product> list = mapper.select();


        String html = "<table border='1'>";
        html+="<caption>商品列表</caption>";
        html+="<tr><th>id</th><th>商品标题</th><th>价格</th><th>库存</th><th>操作</th></tr>";
        for (Product product : list){
            html+="<tr>";
            html+="<td>"+product.getId()+"</td>";
            html+="<td>"+product.getTitle()+"</td>";
            html+="<td>"+product.getPrice()+"</td>";
            html+="<td>"+product.getNum()+"</td>";
            html+="<td>"+"<a href='/delete?id="+product.getId()+"'>删除</a>"+"</td>";
            html+="</tr>";

        }
        html+="</table>";
        return html;

    }

    @RequestMapping("/delete")
    public String delete(int id){
        System.out.println("id=" + id);
        mapper.deleteById(id);
        return "删除完成!<a href='/select'>返回列表页面</a>";
    }

    @RequestMapping("/update")
    public String update(Product product){
        System.out.println("product=" + product);
        mapper.updateById(product);
        return "修改完成!<a href='/select'>返回列表页面</a>";
    }



}
